import axios, {Axios} from 'axios'
import {BASE_URL} from '@/api/config'
import {message} from 'ant-design-vue'
import router from '@/router'


// 超时时间
const instance: Axios = axios.create({
    baseURL: BASE_URL,
    timeout: 50000
})


// http请求拦截器
instance.interceptors.request.use(config => {
    let token = sessionStorage.getItem('token')
    if (token) {
        // @ts-ignore
        config.headers.Authorization = token
    }
    return config
})

// http响应拦截器
instance.interceptors.response.use(
    (res) => {

        if (res.headers.authorization) {
            sessionStorage.setItem('token', res.headers.authorization)
        }

        return res
    },
    (error) => {
        if (error.response.data.data.error == 'UnauthorizedException') {
            router.replace('/login')
            message.error(error.response.data.data.message)
        }
        return Promise.reject(error.response)
    }
)

export default instance
